package org.ilead.iserve.web;

import java.util.Date;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.ilead.iserve.model.SystemMessage;
import org.ilead.iserve.model.base.PageView;
import org.ilead.iserve.service.ISystemMessagePageService;
import org.ilead.iserve.service.ISystemMessageService;
import org.ilead.iserve.service.manager.MessageManager;
import org.ilead.iserve.web.base.BaseActionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;

/**
 * 系统信件Action
 * @author jill
 *
 */
public class SystemMessageAction extends BaseActionSupport {
	private static Logger logger = LoggerFactory.getLogger(SystemMessageAction.class);
	
	private ISystemMessageService systemMessageService;
	@Autowired
	private ISystemMessagePageService systemMessagePageService;

	/**
	 * 系统信件对象，用于增加
	 */
	private SystemMessage m = new SystemMessage();
	
	public ISystemMessageService getSystemMessageService() {
		return systemMessageService;
	}

	public String listSystemMessage(){
		/**
		 * 下面3句固定
		 */
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		int maxResult = 20;
		/**
		 * 修改Bean和service即可
		 */
		PageView<SystemMessage> pageView = new PageView<SystemMessage>(maxResult, getPage());
		LinkedHashMap<String, String> orderMap = new LinkedHashMap<String, String>();
		orderMap.put("sendTime", "desc");
		
		pageView.setQueryResult(systemMessagePageService.getScrollData(pageView.getFirstResult(), maxResult, null,null, orderMap));
		
		/**
		 * request.setAttribute("pageView", pageView)中key尽量为pageView，不然需要修改代码
		 */
		request.setAttribute("pageView", pageView);
		
		//将显示的列表全部标为已读
		MessageManager.getInstance().readListSystemMessage(pageView.getRecords());
		
		return SUCCESS;
	}
	
	public String systemMessage(){
		return SUCCESS;
	}
	
	public String sendSystemMessage(){
		m.setSendTime(new Date());
		try {
			systemMessageService.addMessage(m);
			return SUCCESS;
		} catch (Exception e) {
			logger.error("发送系统信件出错，错误原因:\n", e);
			return ERROR;
		}
	}

	public SystemMessage getM() {
		return m;
	}

	public void setM(SystemMessage m) {
		this.m = m;
	}
}
